package top.kaoshanji.s1ch09a;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/30 15:46
 */
@Controller
public class LoginController {

    // 注入一个请求作用域的bean
    private final LoginProcessor loginProcessor;

    public LoginController(LoginProcessor loginProcessor) {
        this.loginProcessor = loginProcessor;
    }

    @GetMapping("/")
    public String loginGet() {
        return "login.html";
    }

    /**
     * 代码清单-s1ch09a-01：使用请求作用域bean的地方
     * @param username
     * @param password
     * @param model
     * @return
     */
    @PostMapping("/")
    public String loginPost(@RequestParam String username, @RequestParam String password, Model model) {

        // 上面将此对象注入进来了，然后使用set方法赋值
        loginProcessor.setUsername(username);
        loginProcessor.setPassword(password);

        // 那么，此时调用该方法，就是有值的了..嗯..对象 --> 为属性赋值 --> 逻辑方法
        boolean loggedIn = loginProcessor.login();

        if (loggedIn) {
            model.addAttribute("message", "You are now logged in.");
        } else {
            model.addAttribute("message", "Login failed!");
        }

        return "login.html";

    }



}
